#include "field.h"

#include <assert.h>
#include <stdio.h>

char field[NROWS][NCOLS];

//-------------------------------------------------------------------

void new_game()
{
	for(int i=0; i < NROWS; i++)
	{
		for(int j=0; j < NCOLS; j++)
		{
			field[i][j] = EMPTY;
		}
	}
}

//-------------------------------------------------------------------

void put( int row, int column, char what )
{
	assert(row >= 0 && column >= 0 && row < NROWS && column < NCOLS);

	field[row][column] = what;
}

//-------------------------------------------------------------------

char check_state()
{
    for( int i=0; i < NROWS; i++ )
    {
        if( field[i][0] == CROSS && field[i][1] == CROSS && field[i][2] == CROSS )
            return CROSS_WIN;
        if( field[i][0] == ZERO && field[i][1] == ZERO && field[i][2] == ZERO )
            return ZERO_WIN;
    }

    for( int j=0; j < NCOLS; j++ )
    {
        if( field[0][j] == CROSS && field[1][j] == CROSS && field[2][j] == CROSS )
            return CROSS_WIN;
        if( field[0][j] == ZERO && field[1][j] == ZERO && field[2][j] == ZERO )
            return ZERO_WIN;
    }

    if( field[0][0] == CROSS && field[1][1] == CROSS && field[2][2] == CROSS )
        return CROSS_WIN;
    else if( field[0][0] == ZERO && field[1][1] == ZERO && field[2][2] == ZERO )
        return ZERO_WIN;
    else if( field[0][2] == CROSS && field[1][1] == CROSS && field[2][0] == CROSS )
        return CROSS_WIN;
    else if( field[0][2] == ZERO && field[1][1] == ZERO && field[2][0] == ZERO )
        return ZERO_WIN;

    for( int i = 0; i < NROWS; i++ )
    {
        for( int j = 0; j < NCOLS; j++ )
        {
            if( field[i][j] == EMPTY )
                return NOTHING;
        }
    }

    return TIE;
}

//-------------------------------------------------------------------

void draw()
{
	printf("\n");

	for(int i=0; i < NROWS; i++)
	{
		for(int j=0; j < NCOLS; j++)
		{
			if( field[i][j] == CROSS )
				printf("X ");
			else if( field[i][j] == ZERO)
				printf("O ");
			else
				printf("_ ");
		}
		printf("\n");
	}
}

//-------------------------------------------------------------------
